import React, { useState } from 'react'
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Checkbox, Flex, Form, Input, message } from 'antd';
import style from '../style/login.module.less'
import { useNavigate } from 'react-router-dom';
import request from '../utils/request';
import { useDispatch } from 'react-redux';
import { UserActionType } from '../store/userReducer';

const Login: React.FC = () => {
  const [captchaKey, setCaptchaKey] = useState(Date.now())
  const navigate = useNavigate();
  const dispatch = useDispatch()

  const onFinish = (values: any) => {
    async function fetchLogin() {
      const result = await request('/api/admin/login', {
        data: values,
        method: 'POST'
      })
      if(result.data.msg === '') {
        dispatch({
          type: UserActionType.SET_USER,
          payload: result.data.data
        })
        navigate('/bloglist')
      } else {
        message.error(result.data.msg)
        setCaptchaKey(Date.now())
      }
    }
    fetchLogin()
  };
  
  const handleClickImg = () => {
    setCaptchaKey(Date.now())
  }

  return (
    <div className={style.loginPage}>
      <div className={style.loginContainer}>
        <Form
          layout={'vertical'}
          initialValues={{ remember: true }}
          onFinish={onFinish}
        >
          <Form.Item
            name="username"
            label='用户名'
            rules={[{ required: true, message: '请输入用户名!' }]}
          >
            <Input placeholder="用户名" />
          </Form.Item>
          <Form.Item
            name="password"
            label='密码'
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input type="password" placeholder="密码"/>
          </Form.Item>
          <div style={{display: 'flex'}}>
            <Form.Item
              style={{flex: 1}}
              name="captcha"
              label='验证码'
              rules={[{ required: true, message: '请输入验证码!' }]}
            >
              <Input placeholder="验证码" />
            </Form.Item>
            <div>
              <img 
                style={{height: 62}}
                src={`/api/admin/captcha?key=${captchaKey}`} 
                alt='captcha' 
                onClick={handleClickImg}
              />
            </div>
          </div>
          <Form.Item name="remember" valuePropName="checked" noStyle>
            <Checkbox>记住我</Checkbox>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" className="login-form-button">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
export default Login